package com.qf.controller;

import cn.com.webxml.MobileCodeWSSoap;
import com.github.pagehelper.PageInfo;
import com.qf.bean.*;
import com.qf.service.DeptService;
import com.qf.service.EmployeeService;
import com.qf.service.RoleService;
import com.qf.utils.ExcelUtils;
import com.qf.utils.constant.EmployeeEnum;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.dc.pr.PRError;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 19/11/2019
 * Echo
 * qmxc
 * Alibaba
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MobileCodeWSSoap soap;

    @RequestMapping("/phone")
    @ResponseBody
    public Message phone(String phone) {
        Message message = new Message();
        String info = soap.getMobileCodeInfo(phone, "");
        System.out.println("11111111111111111111111111"+info);
        if(info.equals("没有此号码记录")){
            message.setMessage(info);
        }else if (info.equals("手机号码错误 http://www.webxml.com.cn")){
           message.setMessage(info);
        }else{
            String[] strings = info.split("：");
            String p=strings[1];
            message.setMessage(p);
        }
        return message;

    }

    //    @RequestMapping("/login")
//    public String login(String username, String password, HttpServletRequest request) {
//        Employee employee = employeeService.login(username, password);
//        if (employee != null) {
//            HttpSession session = request.getSession();
//            session.setAttribute("user", employee);
//            Role role = employee.getRole();
//            List<Menu> menuList = role.getMenuList();
//            for (Menu menu : menuList) {
//                System.out.println(menu);
//            }
//            return "redirect:/index.jsp";
//        }
//        return "redirect:/login.jsp";
//    }
    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws Exception {
        String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
        if (shiroLoginFailure != null) {
            if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
                throw new Exception("用户名不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
                throw new Exception("密码错误");
            } else {
                throw new Exception("未知异常");
            }
        }
        return "login";
    }

    @RequestMapping("/exit")
    public String exit(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "redirect:/login.jsp";
    }


    @RequestMapping("/resource/demo2/pageShow")
    @RequiresPermissions("user:selectall")
    public String show(ModelMap map, @RequestParam(defaultValue = "1") Integer index, String username, String rolename, String deptname) {
        PageInfo<Employee> pageInfo = employeeService.show(index, username, rolename, deptname);
        List<Employee> list = pageInfo.getList();
        for (Employee employee : list) {
            System.out.println(employee);
        }
        map.addAttribute("info", pageInfo);
        map.addAttribute("username", username);
        map.addAttribute("rolename", rolename);
        map.addAttribute("deptname", deptname);
        return "resource/demo2/list";
    }

    @RequiresPermissions("user:add")
    @RequestMapping("/resource/demo2/addEmp")
    public String addEmp(Employee employee) {
        employee.setCreatedate(new Date());
        employee.setState(1);
        int add = employeeService.addEmp(employee);
        if (add > 0) {
            return "redirect:/resource/demo2/pageShow";
        } else {
            return "redirect:/Resource/demo2/deptList";
        }
    }

    @RequiresPermissions("user:findempnum")
    @RequestMapping("/resource/demo2/findNum")
    @ResponseBody
    public Employee findNum(String numval) {
        Employee employee = employeeService.findNum(numval);
        System.out.println(employee);
        return employee;
    }

    @RequiresPermissions("user:showback")
    @RequestMapping("/resource/demo2/findById")
    public String findById(Integer id, ModelMap map) {
        Employee employee = employeeService.findById(id);
        System.out.println(employee);
        map.addAttribute("emp", employee);
        List<Dept> deptList = deptService.findDeptList();
        for (Dept dept : deptList) {
            System.out.println(dept);
        }
        map.addAttribute("dlist", deptList);
        List<Role> roleList = roleService.findByDid(employee.getRoleid());
        map.addAttribute("rolList", roleList);
        return "resource/demo2/update";

    }

    @RequiresPermissions("user:update")
    @RequestMapping("/resource/demo2/update")
    public String update(Employee employee) {
        int i = employeeService.update(employee);
        if (i > 0) {
            return "redirect:/resource/demo2/pageShow";
        } else {
            return "redirect:/resource/demo2/findById?id=" + employee.getId();
        }
    }

    @RequiresPermissions("user:delete")
    @RequestMapping("/resource/demo2/deleteById")
    public void deleteById(int id, HttpServletResponse response) {
        PrintWriter writer = null;
        response.setContentType("text/html;charset=utf-8");
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int i = employeeService.deleteById(id);
        if (i > 0) {
            writer.print("<script>alert('删除成功');location.href='/resource/demo2/pageShow';</script>");
        } else {
            writer.print("<script>alert('删除失败');location.href='/resource/demo2/pageShow';</script>");
        }


    }


    @RequiresPermissions("user:deletes")
    @RequestMapping("/resource/demo2/deletebyid")
    public void deleteByIds(int[] empid, HttpServletResponse response, HttpServletRequest request) {
        String method = request.getParameter("method");
        response.setContentType("text/html;charset=utf-8");
        if (method.equals("delete")) {
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            int i = employeeService.deleteByIds(empid, EmployeeEnum.DELETE.getStanum());
            if (i > 0) {
                writer.print("<script>alert('删除成功');location.href='/resource/demo2/pageShow';</script>");
            } else {
                writer.print("<script>alert('删除失败');location.href='/resource/demo2/pageShow';</script>");
            }

        } else if (method.equals("daochu")) {
            try {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddhhmmss");
                String fileName = format1.format(new Date()) + ".xls";
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "utf-8"));

                //导出数据
                //1.查询被选中的数据信息
                List<Employee> employeeList = employeeService.findbyids(empid);
                //2.导出数据
                ExcelUtils.createFirst("用户信息");
                ExcelUtils.createOthers(employeeList);
                //"f://" + (format.format(new Date())) + ".xls"
                ServletOutputStream outputStream = response.getOutputStream();
                ExcelUtils.export(outputStream);
//                outputStream.print("<script>alert('导出成功');location.href='/resource/demo2/pageShow'</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
